package com.app.couponsharelife.ui.main.me.phonenum

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.viewmodel.MeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_update_phone_num.*
import kotlinx.android.synthetic.main.common_tool_bar_layout.*
import java.util.HashMap
import java.util.concurrent.TimeUnit

class UpdatePhoneNumActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_update_phone_num

    private var phone = ""

    private var mViewModel: MeViewModel? = null

    private var disposable: Disposable? = null

    private var countDownNum: Int = -1

    override fun initViews() {
        if (intent.getStringExtra("phone") != null && intent.getStringExtra("phone") != "") {
            phone = intent.getStringExtra("phone")
            if (phone.length == 11) {
                val start = phone.substring(0, 3)
                val end = phone.substring(7)
                tvOldPhoneNum.text = String.format("原手机号：${start}****$end")
            } else {
                showToastMsg("数据错误，请退出重试")
                finish()
            }
        } else {
            showToastMsg("数据错误，请退出重试")
            finish()
        }
        initToolBar()
        tvGetCheckCodeBtn.setOnClickListener {
            sendCheckCode()
        }
        tvConfirmBindBtn.setOnClickListener {
            getUserIsCorrect()
        }
        watchEditText(etCheckCode)
    }

    private fun initToolBar() {
        ivBack.setOnClickListener { finish() }
        tvToolBarTitle.text = "修改手机号"
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(MeViewModel::class.java)
        if (!mViewModel!!.sendCheckCode()!!.hasObservers()) {
            mViewModel!!.sendCheckCode()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSendCheckCode(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSendCheckCode(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshSendCheckCode(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            sendCheckCodeSuccess()
                        } else {
                            showToastMsg("发送失败")
                        }
                    }
                }
            })
            mViewModel!!.getUserIsCorrect()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetUserIsCorrect(hashMapOf(), false)
                        showToastMsg(parseErrorDate(it.error!!.message).tip)
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetUserIsCorrect(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.freshGetUserIsCorrect(hashMapOf(), false)
                        if (it.data!!.code == 200) {
                            startActivity(Intent(this, BindPhoneNumActivity::class.java))
                            finish()
                        } else {
                            showToastMsg("验证失败")
                        }
                    }
                }
            })
        }
    }

    private fun sendCheckCode() {
        val map = HashMap<String, String>()
        map["mobile"] = phone
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshSendCheckCode(map, true)
    }

    private fun getUserIsCorrect() {
        if (TextUtils.isEmpty(etCheckCode.text)) {
            showToastMsg("请输入验证码")
            return
        }
        val map = HashMap<String, String>()
        map["mobile"] = phone
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["code"] = etCheckCode.text.toString().trim()
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.freshGetUserIsCorrect(map, true)
    }

    private fun sendCheckCodeSuccess() {
        countDownNum = 59
        tvCheckCodeNum.visibility = View.VISIBLE
        tvGetCheckCodeBtn.visibility = View.INVISIBLE
        tvGetCheckCodeBtn.isClickable = false
        disposable = Observable.interval(0, 1, TimeUnit.SECONDS)//10s 倒计时
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ aLong ->
                    if (countDownNum < 0)
                        goAhead()
                    else {
                        tvCheckCodeNum.text = "${countDownNum}s后重发"
                        countDownNum--
                    }
                }) { goAhead() }
    }

    private fun goAhead() {
        tvCheckCodeNum.visibility = View.INVISIBLE
        tvGetCheckCodeBtn.visibility = View.VISIBLE
        tvGetCheckCodeBtn.isClickable = true
        disposable?.dispose()
        disposable == null
    }

    override fun onDestroy() {
        if (disposable != null && !disposable!!.isDisposed) {
            disposable?.dispose()
            disposable == null
        }
        super.onDestroy()
    }

    private fun watchEditText(editText: EditText) {
        editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                if (TextUtils.isEmpty(editText.text)) {
                    tvConfirmBindBtn.setBackgroundResource(R.drawable.btn_bg2)
                    tvConfirmBindBtn.text = "验证后绑定"
                } else {
                    tvConfirmBindBtn.setBackgroundResource(R.drawable.btn_bg1)
                    tvConfirmBindBtn.text = "确定绑定"
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
        })
    }
}
